var redis = require("redis");
// 创建一个使用Node.js缓冲区而不是JavaScript字符串的Redis客户端 - 这一行与前面的示例不同。
// 使用缓冲区来处理字符串比使用JavaScript字符串更简单。
var client = redis.createClient({ return_buffers: true });

// 函数storeDailyVisit使用命令SETBIT来保存在给定日期访问过网站的用户的给定用户ID
function storeDailyVisit(date, userId) {
    var key = 'visits:daily:' + date;
    client.setbit(key, userId, 1, function (err, reply) {
        console.log("User", userId, "visited on", date);
    })
}

// 函数countVisits使用命令BITCOUNT来计算在给定日期访问过网站的用户数
function countVisits(date) {
    var key = 'visits:daily:' + date;
    client.bitcount(key, function (err, reply) {
        console.log(date, "had", reply.toString(), "visits.");
    });
}


// showUserIdsFromVisit显示在给定日期访问过网站的所有用户的用户ID
function showUserIdsFromVisit(date) {
    var key = 'visits:daily:' + date;
    client.get(key, function (err, bitmapValue) {
        var userIds = [];
        var data = bitmapValue.toJSON().data;
        data.forEach(function (byte, byteIndex) {
            console.log("byte:", byte, " Index:", byteIndex);
            for (var bitIndex = 7; bitIndex >= 0; bitIndex--) {
                var visited = byte >> bitIndex & 1;
                if (visited === 1) {
                    var userId = byteIndex * 8 + (7 - bitIndex);
                    userIds.push(userId);
                }
            }
        });
        console.log("Users " + userIds + " visited on " + date);
    });
}

storeDailyVisit('2015-01-01', '1');
storeDailyVisit('2015-01-01', '2');
storeDailyVisit('2015-01-01', '10');
storeDailyVisit('2015-01-01', '55');
countVisits('2015-01-01');
showUserIdsFromVisit('2015-01-01');
client.quit();
